package com.filetransfer.api;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URL;
import java.util.Random;
@Slf4j
public class test {
    public static void main(String[] args) {
        // 文件参数
        String filePath = "random_file.bin"; // 文件路径
        long fileSize = 1024 * 1024 * 10 + 1025;    // 文件大小（10 MB）
        try {
            var file = new File(filePath);
            if (!file.exists()) {
                generateRandomFile(filePath, fileSize);
                log.info("随机文件已生成：" + filePath);
            }
        } catch (IOException e) {
            log.error("生成随机文件失败", e);
        }
//        var file = new File(filePath);
        int chunkSize = 2 * 1024 * 1024;
        var shareCollection = new ShareCollection(chunkSize);
        shareCollection.addFile(new File(filePath), progressInfo -> {
            log.info("上传进度：" + progressInfo);
        });
        var result = shareCollection.makeShare();
        log.info("分享码：" + result.share());
        for (URL link : result.links()) {
            log.info("下载链接：" + link.toString());
        }
    }
    public static void generateRandomFile(String filePath, long size) throws IOException {
        File file = new File(filePath);
        try (FileOutputStream fos = new FileOutputStream(file)) {
            Random random = new Random();
            byte[] buffer = new byte[1024 * 1024];
            long remaining = size;
            while (remaining > 0) {
                int bytesToWrite = (int) Math.min(buffer.length, remaining);
                random.nextBytes(buffer); // 填充随机字节
                fos.write(buffer, 0, bytesToWrite);
                remaining -= bytesToWrite;
            }
        }
    }
//    public boolean isReachable(String ipAddress) {
//        try {
//            InetAddress address = InetAddress.getByName(ipAddress);
//            log.info("正在尝试连接到设备：" + ipAddress);
//            return address.isReachable(3000); // 超时时间为 3000 毫秒
//        } catch (IOException e) {
//            log.error("无法连接到设备：" + ipAddress);
//            return false;
//        }
//    }
//    boolean is = isReachable("192.168.6.248");
}
